package controller.servlets;

import com.fasterxml.jackson.databind.ObjectMapper;
import dao.AthleteGradeDao;
import modle.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.Serial;
import java.util.List;

@WebServlet(name = "SearchCollegeGradeServlet", value = "/SearchCollegeGrade")
public class SearchCollegeGradeServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int c_id;
        HttpSession session = request.getSession();
        User user = (User)session.getAttribute("user");
        String type = user.getRoletype();
        if(!type.equals("2"))
            c_id = -100;
        else{
            AthleteLeader athleteLeader = (AthleteLeader) session.getAttribute("role");
            c_id = athleteLeader.getCollegeID();
        }
        AthleteGradeDao athleteGradeDao = new AthleteGradeDao();
        List<AthleteCompetitionGrade> dataList = athleteGradeDao.getSearchCollegeCompetitionGrade(c_id);

        // 将Java对象转换为JSON字符串
        ObjectMapper mapper = new ObjectMapper();
//        String jsonString = mapper.writeValueAsString(dataList);
        String code = "{\"code\": 0, \"msg\": \"\", \"count\": " + dataList.size() + ", \"data\":";
        String jsonString = ParamsUtil.objectToJsonStr(dataList);
        // 设置响应的Content-Type并将JSON字符串写入输出流
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(code + jsonString + "}");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
